import { forEach, isEmpty, isNumber, join, last, map, padEnd, reduce } from 'lodash'
import { ObjectType } from 'typings/interfaces'
import { h } from 'vue'
import {tips} from "@/views/science/components/tips/tips";

/**
 * url地址拼接数组
 * @param url url地址
 * @param params 参数
 * @returns string
 */
export const stringifyUrl = (url: string, params: { [x: string]: string[] }) =>
  url +
  '?' +
  join(
    map(Object.values(params), (value) => encodeURI(`${Object.keys(params)}[]=${value}`)),
    '&'
  )

/**性能监测 */
export function observePerformance() {
  const observer = new PerformanceObserver((list) => {
    console.log('监测到长任务! 🚩️')
    const entries = list.getEntries()
    console.log(entries)
  })
  observer.observe({ type: 'longtask', buffered: true })
}

/**
 * 树节点找到某个节点
 * @param root tree节点 ObjectType[]
 * @param params ObjectType
 * @returns ObjectType
 */
export function findNode(root: any, params: { [x: string]: string }): ObjectType {
  const stack: ObjectType = [...root]
  const key = Object.keys(params)[0]
  let node
  stack.push(root)
  while (stack.length > 0) {
    node = stack.pop()
    if (node[key] == params[key]) {
      return node
    } else if (!isEmpty(node.children)) {
      forEach(node.children, (item) => stack.push(item))
    }
  }
  return {}
}

/**
 * 渲染数据状态
 * @param status 审批状态
 * @param statusName 审批状态名称
 * @returns VNode
 */
export function renderStatusName(status: 0 | 1 | 2, statusName: string) {
  const color = {
    0: '#bfbfbf',
    1: '#faad14',
    2: '#52c41a',
  }
  return h(
    'span',
    {
      style: {
        color: color[status],
      },
    },
    statusName
  )
}

/**
 * 格式化桩号
 * @param stake 桩号
 * @param prefix 桩号前缀
 * @returns string
 */
export function formatStake(stake: number, prefix: string) {
  if (isNumber(stake)) {
    const decimals = stake.toFixed(3).split('.')[1]
    const num = stake / 1000
    const trunc = Math.trunc(num)
    const fract = (value: number) => {
      if (value < 10) return `00${value}`
      if (value < 100) return `0${value}`
      return value
    }
    return `${prefix}${trunc}+${fract(Math.floor((num - trunc) * 1000))}.${decimals}`
  }
  return stake
}

/**
 * 处理表单项
 * @param items 表单项
 * @returns Record<FormItemKey, undefined>
 */
export const handleFormItems = (items: Record<'key', string>[]): Record<string, undefined> =>
  reduce(
    items,
    (total, { key }) => {
      return {
        ...total,
        [key]: undefined,
      }
    },
    {}
  )
// 终点桩号和起点桩号的差值 单位m
export const differenceStake = (startStake: number, endStake: number): number => {
  if (isNumber(startStake) && isNumber(endStake) && endStake > startStake) {
    return Number((endStake - startStake).toFixed(3))
  } else {
    return 0
  }
}

// 获取最后一级行政区域代码
export const lastRegionCode = (regionCodeArray: Array<string>): string =>
  last(regionCodeArray) || ''

// 根据最后一级行政区域代码补全级联数据
export const expandRegionCode = (regionCode: string): Array<string> => {
  if (regionCode && regionCode !== '000000000000') {
    const provinceCode = padEnd(regionCode.substring(0, 2), 12, '0')
    const cityCode = padEnd(regionCode.substring(0, 4), 12, '0')
    return [provinceCode, cityCode, regionCode]
  }
  return []
}

// 根据机构id获取机构信息
export const getNode = (data: ObjectType[], id: string) => {
  for (let i = 0; i < data.length; i++) {
    const e = data[i]
    if (e.id === id) {
      return e
    } else if (e.children) {
      return getNode(e.children, id)
    }
  }
  return undefined
}

// 手机号校验
export const validatePhoneNumber = (phoneNumber) => {
  if (phoneNumber.length !== 11) {
    return false;
  }
  const reg = /^1\d{10}$/;
  return reg.test(phoneNumber);
}
// 手机号校验
export const validatePhoneNumbertwo = (phoneNumber) => {
  if (phoneNumber.length !== 11) {
    return false;
  }
  const reg = /^1[3456789]\d{0,9}$/;
  return reg.test(phoneNumber);
/*  if(phoneNumber.substring(0,1) !== '1'){

    return false;
  }
  phoneNumber = phoneNumber.replace(/[^\d]/g, ''); // 只允许输入数字
  if (!/^1[3456789]\d{0,9}$/.test(phoneNumber)) {
    tips('请输入正确的电话号码', 'error');
    return false;
  }*/
}




